Java Encapsulation

One of the most important aspects of object-oriented programming is encapsulation. Encapsulation is the technique of combining code and data into a single unit.

In java, it groups the fields and methods within a single class.

With the help of encapsultation, we can control the access of data inside the class.

We use the private access modifier to control the access of data in a class from being accessing by other classes.

Example for encapsulation

class Employee {
  private String empName;

  public String getName() {
    return empName;
  }

  public void setName(String name) {
    this.empName = name;
  }
}

class Main {
  public static void main(String[] args) {
    //creating instance of the encapsulated class  
    Employee empObj = new Employee();
    //setting the name of the employee
    empObj.setName("Andrew Rayan");
    //getting the name of the employee
    System.out.println(empObj.getName());
  }
}

Output

Andrew Rayan

In the above example, we have created a class Employee with a private string variable empName. The class also contains two methods setName() and getName().

The setName() method is used to get a string a parameter and sets the value of the private variable empName.

The getName() method is used to get value of the empName variable.

In the Main class, we create an object for the Employee class and call setName() method to set the name of the private variable empName.

Now, using the getName() method we get the value of the private variable empName.

If we try to access the empName with the object of the Employee class directly, then it will throw an error.

Main.java:18: error: empName has private access in Employee
empObj.empName = "Andrew Rayan";

So, this way we can hide the data of the class, we call this as data hiding.


Most Read